package com.springchang.leetcode.sword2offer;

/**
 * 剑指 Offer 06. 从尾到头打印链表
 * 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 */
public class Offer06 {
    public int[] reversePrint(ListNode head) {

        //定义一个栈
        java.util.Stack<Integer> integerStack = new java.util.Stack<>();
        //定义一个变量记录当前节点
        ListNode currentNode = head;

        while (currentNode != null) {
            integerStack.push(currentNode.val);
            currentNode = currentNode.next;
        }

        int[] result = new int[integerStack.size()];

        int index = 0;
        while (!integerStack.isEmpty()) {
            result[index++] = integerStack.pop();
        }

        return  result;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(2);
        ListNode node1 = new ListNode(3);
        ListNode node2 = new ListNode(1);
        head.next = node1;
        node1.next = node2;

        Offer06 testCase = new Offer06();

        //测试用例1
        System.out.println(testCase.reversePrint(head));
        //测试用例2
        System.out.println(testCase.reversePrint(null));
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

